"""
Authentication API Routes for TaskMaster v1
AceFlow v3.0 - Implementation Phase

Provides user registration and login endpoints
"""

from fastapi import APIRouter, HTTPException, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, EmailStr
from typing import Optional
from ..services.user_service import get_user_service
from ..utils.auth_utils import get_user_id_from_token

# Create router
router = APIRouter()
security = HTTPBearer()

# Pydantic models for request/response
class UserRegisterRequest(BaseModel):
    username: str
    password: str
    email: Optional[EmailStr] = None

class UserLoginRequest(BaseModel):
    username: str
    password: str

class UserRegisterResponse(BaseModel):
    success: bool
    message: str
    user_id: Optional[int]

class UserLoginResponse(BaseModel):
    success: bool
    message: str
    token: Optional[str]
    user_id: Optional[int]

class UserInfoResponse(BaseModel):
    id: int
    username: str
    email: Optional[str]
    avatar: Optional[str]
    created_at: str


# Dependency to get current user
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
    """Get current authenticated user"""
    token = credentials.credentials
    user_id = get_user_id_from_token(token)

    if not user_id:
        raise HTTPException(
            status_code=401,
            detail="Invalid authentication token",
            headers={"WWW-Authenticate": "Bearer"},
        )

    return user_id


@router.post("/register", response_model=UserRegisterResponse)
async def register_user(request: UserRegisterRequest):
    """
    Register a new user

    This endpoint allows new users to create an account.
    Username must be unique across the system.
    """
    user_service = get_user_service()
    result = user_service.register_user(
        username=request.username,
        password=request.password,
        email=request.email
    )

    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["message"])

    return UserRegisterResponse(**result)


@router.post("/login", response_model=UserLoginResponse)
async def login_user(request: UserLoginRequest):
    """
    Authenticate user login

    This endpoint validates user credentials and returns a JWT token
    for authenticated requests.
    """
    user_service = get_user_service()
    result = user_service.authenticate_user(
        username=request.username,
        password=request.password
    )

    if not result["success"]:
        raise HTTPException(status_code=401, detail=result["message"])

    return UserLoginResponse(**result)


@router.get("/me", response_model=UserInfoResponse)
async def get_current_user_info(user_id: int = Depends(get_current_user)):
    """
    Get current user information

    This endpoint returns the authenticated user's profile information.
    Requires valid JWT token in Authorization header.
    """
    user_service = get_user_service()
    user_info = user_service.get_user_by_id(user_id)

    if not user_info:
        raise HTTPException(status_code=404, detail="User not found")

    return UserInfoResponse(**user_info)
